package com.xinggq.pay.service.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xinggq.common.CommonResult;
import com.xinggq.common.enums.ResponseEnum;
import com.xinggq.pay.service.config.AppIdValidationConfig;
import com.xinggq.pay.service.context.AppIdContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 应用ID拦截器
 * 在请求开始时从请求头或参数中获取appId并设置到ThreadLocal中
 * 根据配置校验特定路径是否必须提供appId
 * 在请求结束时清理ThreadLocal，避免内存泄漏
 *
 * @author system
 * @since 2025/1/10
 */
@Slf4j
@Component
@Order(1)
@RequiredArgsConstructor
public class AppIdInterceptor implements HandlerInterceptor {

    private final AppIdValidationConfig appIdValidationConfig;
    private final ObjectMapper objectMapper;

    /**
     * 请求头中的应用ID字段名
     */
    private static final String APP_ID_HEADER = "X-App-Id";
    
    /**
     * 请求参数中的应用ID字段名
     */
    private static final String APP_ID_PARAM = "appId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String requestPath = request.getRequestURI();
        
        // 优先从请求头获取appId
        String appIdStr = request.getHeader(APP_ID_HEADER);
        
        // 如果请求头中没有，则从请求参数中获取
        if (appIdStr == null || appIdStr.trim().isEmpty()) {
            appIdStr = request.getParameter(APP_ID_PARAM);
        }
        
        // 解析并设置appId到ThreadLocal中
        Long appId = null;
        if (appIdStr != null && !appIdStr.trim().isEmpty()) {
            try {
                appId = Long.valueOf(appIdStr.trim());
                AppIdContext.setAppId(appId);
                log.debug("设置应用ID到ThreadLocal: {}", appId);
            } catch (NumberFormatException e) {
                log.warn("应用ID格式错误: {}", appIdStr, e);
                // 如果需要校验appId的路径，格式错误也视为无效
                if (appIdValidationConfig.isAppIdRequired(requestPath)) {
                    writeErrorResponse(response, "应用ID格式错误");
                    return false;
                }
            }
        }
        
        // 校验是否需要appId
        if (appIdValidationConfig.isAppIdRequired(requestPath)) {
            if (appId == null) {
                log.warn("请求路径 {} 需要提供应用ID，但未找到有效的应用ID", requestPath);
                writeErrorResponse(response, "请求需要提供有效的应用ID");
                return false;
            }
            log.debug("请求路径 {} 校验应用ID通过: {}", requestPath, appId);
        } else {
            log.debug("请求路径 {} 无需校验应用ID", requestPath);
        }
        
        return true;
    }

    /**
     * 写入错误响应
     *
     * @param response HTTP响应
     * @param message  错误消息
     * @throws IOException IO异常
     */
    private void writeErrorResponse(HttpServletResponse response, String message) throws IOException {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        
        CommonResult<Void> result = CommonResult.fail(ResponseEnum.APP_ID_NOT_FOUND);
        String jsonResponse = objectMapper.writeValueAsString(result);
        
        response.getWriter().write(jsonResponse);
        response.getWriter().flush();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 清理ThreadLocal，避免内存泄漏
        AppIdContext.clear();
        log.debug("清理ThreadLocal中的应用ID");
    }
}